require('dotenv').config(); // 必须放在最前面，加载环境变量
const express = require('express');
const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs'); // 密码加密
const session = require('express-session'); // 会话管理
const bodyParser = require('body-parser'); // 解析表单数据
const OpenAI = require('openai'); // DeepSeek API
const app = express();
const port = 3000;

// 配置中间件
app.use(bodyParser.urlencoded({ extended: true })); // 解析表单数据
app.use(bodyParser.json()); // 解析JSON数据
app.use(session({
    secret: 'your_secret_key', // 自定义密钥（用于加密会话）
    resave: false,
    saveUninitialized: false,
    cookie: { secure: false } // 本地开发用false，生产环境需设为true（HTTPS）
}));

// 数据库配置
const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: '1234',
    database: 'admin_system'
};

// DeepSeek API 配置
const openai = new OpenAI({
    baseURL: 'https://api.deepseek.com',
    apiKey: process.env.DEEPSEEK_API_KEY || 'sk-your-api-key-here', // 请替换为实际的API密钥
});

// 验证API密钥是否加载
console.log('DeepSeek API密钥状态:', process.env.DEEPSEEK_API_KEY ? '✅ 已加载' : '❌ 未加载');

// 1. 登录接口（处理前端登录请求）
app.post('/api/login', async (req, res) => {
    const { username, password } = req.body;
    console.log('前端提交的用户名:', username);
    console.log('前端提交的密码:', password);

    try {
        const connection = await mysql.createConnection(dbConfig);
        const [users] = await connection.execute(
            'SELECT * FROM user WHERE username = ?',
            [username]
        );
        connection.end();

        if (users.length === 0) {
            return res.json({ success: false, message: '用户名不存在' });
        }

        const user = users[0];
        console.log('数据库中的密码哈希:', user.password); // 应与新生成的哈希完全一致
        const isPasswordValid = await bcrypt.compare(password, user.password);
        console.log('密码比对结果:', isPasswordValid); // 应为true

        if (!isPasswordValid) {
            return res.json({ success: false, message: '密码错误' });
        }

        req.session.user = { id: user.id, username: user.username };
        return res.json({ success: true, message: '登录成功' });

    } catch (err) {
        console.error('登录失败:', err);
        return res.json({ success: false, message: '服务器错误' });
    }
});

// 2. 注册接口（处理前端注册请求）
app.post('/api/register', async (req, res) => {
    const { username, password } = req.body;
    console.log('注册请求 - 用户名:', username);

    // 后端验证
    if (!username || !password) {
        return res.json({ success: false, message: '用户名和密码不能为空' });
    }

    if (username.trim().length < 3) {
        return res.json({ success: false, message: '用户名长度至少为3位' });
    }

    if (password.length < 6) {
        return res.json({ success: false, message: '密码长度至少为6位' });
    }

    try {
        const connection = await mysql.createConnection(dbConfig);
        
        // 检查用户名是否已存在
        const [existingUsers] = await connection.execute(
            'SELECT id FROM user WHERE username = ?',
            [username]
        );

        if (existingUsers.length > 0) {
            connection.end();
            return res.json({ success: false, message: '用户名已存在，请换一个' });
        }

        // 加密密码
        const hashedPassword = await bcrypt.hash(password, 10);
        console.log('生成的密码哈希:', hashedPassword);

        // 插入新用户
        await connection.execute(
            'INSERT INTO user (username, password) VALUES (?, ?)',
            [username, hashedPassword]
        );
        
        connection.end();
        console.log('用户注册成功:', username);
        return res.json({ success: true, message: '注册成功' });

    } catch (err) {
        console.error('注册失败:', err);
        return res.json({ success: false, message: '服务器错误，请重试' });
    }
});


// 确保requireLogin中间件明确返回未登录提示
const requireLogin = (req, res, next) => {
    if (req.session.user) {
        next();
    } else {
        res.status(401).json({ success: false, message: '未登录，请先登录' });
    }
};



//  托管静态文件（登录页、单词页等）
app.use(express.static('public'));

// 启动服务
app.listen(port, () => {
    console.log(`服务运行在 http://localhost:${port}`);
});



// 3. 记录用户“已掌握”单词
// 修改server.js中记录“已掌握”单词的接口
app.post('/api/record-learned', requireLogin, async (req, res) => {
    const { userId, wordId, bookId, status } = req.body;

    if (!userId || !wordId || !bookId || status === undefined) {
        return res.json({ success: false, message: '参数不完整' });
    }

    try {
        const connection = await mysql.createConnection(dbConfig);
        // 关键修改：添加ON DUPLICATE KEY UPDATE处理重复记录
        await connection.execute(
            `INSERT INTO user_learned_word 
       (user_id, word_id, book_id, status, learned_time) 
       VALUES (?, ?, ?, ?, NOW())
       ON DUPLICATE KEY UPDATE  -- 当存在重复记录时执行更新
       status = VALUES(status),  -- 更新状态（保持最新状态）
       learned_time = NOW()`,
            [userId, wordId, bookId, status]
    );
        connection.end();
        res.json({ success: true, message: '记录成功' });
    } catch (err) {
        console.error('记录失败：', err);
        res.json({ success: false, message: '服务器错误' });
    }
});

// 新增：获取当前登录用户信息
app.get('/api/user', requireLogin, (req, res) => {
    res.json({
        id: req.session.user.id,
        username: req.session.user.username
    });
});

// filePath: H5/server.js （修改/api/words接口，添加日志）
app.get('/api/words', requireLogin, async (req, res) => {
    try {
        const { bookId } = req.query;
        console.log('接收到的bookId参数：', bookId); // 打印前端传递的bookId

        const connection = await mysql.createConnection(dbConfig);
        let query = 'SELECT id, wordRank, headWord, content, bookId FROM world';
        const params = [];

        if (bookId) {
            query += ' WHERE bookId = ?';
            params.push(bookId);
        }

        const [rows] = await connection.execute(query, params);
        console.log(`根据bookId=${bookId}查询到的单词数量：`, rows.length);
        console.log('查询到的前3个单词的bookId：', rows.slice(0,3).map(w => w.bookId)); // 检查返回的bookId是否正确

        connection.end();
        res.json(rows);
    } catch (err) {
        console.error('获取单词失败：', err);
        res.status(500).json({ success: false, message: '服务器错误' });
    }
});

// 单词书列表接口
// 修正后的 /api/books 接口（替换原错误代码）
app.get('/api/books', requireLogin, async (req, res) => {
    try {
        // 正确创建数据库连接（使用已配置的 dbConfig）
        const connection = await mysql.createConnection(dbConfig);
        // 查询 book 表的所有单词书（字段与表结构一致）
        const [rows] = await connection.execute(
            'SELECT id, bookId, title, wordCount, coverUrl FROM book'
        );
        connection.end();
        console.log('查询到的单词书数量：', rows.length);
        res.json(rows); // 返回单词书列表给前端
    } catch (err) {
        console.error('查询单词书失败：', err);
        res.status(500).json({ success: false, message: '加载单词书失败' });
    }
});

// 翻译接口(基于DeepSeek API)
app.post('/api/translate', requireLogin, async (req, res) => {
    const { text } = req.body;
    
    if (!text || text.trim() === '') {
        return res.json({ success: false, message: '请输入要翻译的内容' });
    }
    
    try {
        // 检测语言并设置系统提示词
        const isChinese = /[\u4e00-\u9fa5]/.test(text);
        const systemPrompt = isChinese 
            ? '你是一个专业的翻译助手。请将用户输入的中文翻译成地道、自然的英语。只返回翻译结果，不要添加任何解释或额外内容。'
            : '你是一个专业的翻译助手。请将用户输入的英文翻译成通顺、准确的中文。只返回翻译结果，不要添加任何解释或额外内容。';
        
        console.log('翻译请求：', text);
        console.log('检测语言：', isChinese ? '中文' : '英文');
        
        const completion = await openai.chat.completions.create({
            messages: [
                { role: "system", content: systemPrompt },
                { role: "user", content: text }
            ],
            model: "deepseek-chat",
            temperature: 0.3, // 降低随机性，提高翻译准确性
        });
        
        const translation = completion.choices[0].message.content;
        console.log('翻译结果：', translation);
        
        res.json({ 
            success: true, 
            translation: translation,
            detectedLanguage: isChinese ? 'zh' : 'en'
        });
        
    } catch (err) {
        console.error('翻译失败：', err);
        
        // 处理不同类型的错误
        if (err.status === 401) {
            return res.json({ success: false, message: 'API密钥无效，请检查配置' });
        } else if (err.status === 429) {
            return res.json({ success: false, message: 'API调用频率超限，请稍后重试' });
        } else if (err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT') {
            return res.json({ success: false, message: '网络连接失败，请检查网络' });
        }
        
        res.json({ 
            success: false, 
            message: '翻译服务暂时不可用，请稍后重试' 
        });
    }
});

// 查询用户已学单词接口
app.get('/api/learned-words', requireLogin, async (req, res) => {
    const { sortType = 'time_asc' } = req.query;
    const userId = req.session.user.id;
    
    try {
        const connection = await mysql.createConnection(dbConfig);
        
        // 根据sortType构建排序条件
        let orderBy = '';
        switch(sortType) {
            case 'time_desc':
                orderBy = 'ulw.learned_time DESC';
                break;
            case 'letter_asc':
                orderBy = 'w.headWord ASC';
                break;
            case 'letter_desc':
                orderBy = 'w.headWord DESC';
                break;
            case 'time_asc':
            default:
                orderBy = 'ulw.learned_time ASC';
                break;
        }
        
        // 关联查询：从user_learned_word关联world表获取单词详情
        const query = `
            SELECT 
                w.id,
                w.headWord,
                w.bookId,
                ulw.learned_time,
                ulw.status
            FROM user_learned_word ulw
            INNER JOIN world w ON ulw.word_id = w.id
            WHERE ulw.user_id = ? AND ulw.status = 1
            ORDER BY ${orderBy}
        `;
        
        const [rows] = await connection.execute(query, [userId]);
        connection.end();
        
        console.log(`查询到用户${userId}的已学单词数量：`, rows.length);
        res.json({ success: true, words: rows });
        
    } catch (err) {
        console.error('查询已学单词失败：', err);
        res.status(500).json({ success: false, message: '查询失败，请重试' });
    }
});

// 查询复习单词接口（按学习时间倒序）
app.get('/api/review-words', requireLogin, async (req, res) => {
    const userId = req.session.user.id;
    
    try {
        const connection = await mysql.createConnection(dbConfig);
        
        // 关联查询：获取用户已学单词的详细信息（音标和翻译）
        const query = `
            SELECT 
                w.id as word_id,
                w.headWord,
                w.content
            FROM user_learned_word ulw
            INNER JOIN world w ON ulw.word_id = w.id
            WHERE ulw.user_id = ? AND ulw.status = 1
            ORDER BY ulw.learned_time DESC
        `;
        
        const [rows] = await connection.execute(query, [userId]);
        connection.end();
        
        // 处理返回数据，提取音标和翻译
        const words = rows.map(row => {
            const content = row.content;
            return {
                word_id: row.word_id,
                headWord: row.headWord,
                usphone: content?.usphone || '',
                ukphone: content?.ukphone || '',
                transCn: content?.trans?.[0]?.tranCn || ''
            };
        });
        
        console.log(`查询到用户${userId}的复习单词数量：`, words.length);
        res.json(words);
        
    } catch (err) {
        console.error('查询复习单词失败：', err);
        res.status(500).json({ success: false, message: '查询失败，请重试' });
    }
});

// 获取用户已掌握单词列表（用于生成文章）
app.get('/api/learned-words-list', requireLogin, async (req, res) => {
    const userId = req.session.user.id;
    
    try {
        const connection = await mysql.createConnection(dbConfig);
        
        const query = `
            SELECT 
                w.id as word_id,
                w.headWord,
                ulw.book_id
            FROM user_learned_word ulw
            INNER JOIN world w ON ulw.word_id = w.id
            WHERE ulw.user_id = ? AND ulw.status = 1
            ORDER BY w.headWord ASC
        `;
        
        const [rows] = await connection.execute(query, [userId]);
        connection.end();
        
        console.log(`查询到用户${userId}的已学单词列表数量：`, rows.length);
        res.json(rows);
        
    } catch (err) {
        console.error('查询已学单词列表失败：', err);
        res.status(500).json({ success: false, message: '查询失败，请重试' });
    }
});

// 生成文章接口（基于DeepSeek API）
app.post('/api/generate-article', requireLogin, async (req, res) => {
    const { words } = req.body;
    
    if (!words || !Array.isArray(words) || words.length < 5 || words.length > 15) {
        return res.json({ success: false, message: '请选择5-15个单词' });
    }
    
    try {
        const wordList = words.join(', ');
        const systemPrompt = `你是一位专业的英语写作老师。请创作一篇150-200词的英语短文，要求：
1. 必须使用以下所有单词：${wordList}
2. 文章需要连贯、自然，有完整的情节或主题
3. 使用的单词要符合语法和语境
4. 返回格式为JSON：{"article": "英文文章内容", "translation": "中文翻译"}
5. 文章中使用到的指定单词用**单词**格式标记（例如：**happy**）`;
        
        console.log('生成文章请求，单词：', wordList);
        
        const completion = await openai.chat.completions.create({
            messages: [
                { role: "system", content: systemPrompt },
                { role: "user", content: `请用这些单词写一篇英语短文：${wordList}` }
            ],
            model: "deepseek-chat",
            temperature: 0.7,
            response_format: { type: "json_object" }
        });
        
        const result = JSON.parse(completion.choices[0].message.content);
        console.log('文章生成成功');
        
        res.json({ 
            success: true, 
            article: result.article || '',
            translation: result.translation || '',
            words: words
        });
        
    } catch (err) {
        console.error('生成文章失败：', err);
        
        if (err.status === 401) {
            return res.json({ success: false, message: 'API密钥无效，请检查配置' });
        } else if (err.status === 429) {
            return res.json({ success: false, message: 'API调用频率超限，请稍后重试' });
        }
        
        res.json({ 
            success: false, 
            message: '生成文章失败，请重试' 
        });
    }
});